import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form, Input, Button, Modal, Select, Row, Col, InputNumber, Popconfirm, message } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import columnsData, { columnsDataType } from './data'
import { getWithdrawalRataList, addWithdrawalRataInfo, listFeeCategoris, activate, invalidation } from './service'
import TableTitle from '../../../components/TableTitle'
// 国际化配置
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { getCode } from '@/services/generateCode';
import moment from 'moment';

export default () => {
  const { TextArea } = Input;
  const { Option } = Select;
  // 模态框控制
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 添加用户数据表单实例
  const [addFormRef] = Form.useForm();
  // 手续费类型
  const [listFee, setListFee] = useState([])
  // 生效所需编号
  const [feeCde, setFeeCde] = useState('')
  // 新增生效确认模态框
  const [isModalValidation, setIsModalValidation] = useState(false)
  // 新增表单数据储存
  const [response, setResponse] = useState()
  // 控制新增确认按钮loading
  const [addLoading, setAddLoading] = useState(false)

  // 新增按钮
  async function addInfo() {
    setIsModalVisible(true);
    let { body: listFee } = await listFeeCategoris({});
    console.log(listFee);

    setListFee(listFee);
    // 获取配置编码
    let res = await getCode({ type: 1 })
    // 表单赋值配置编码
    addFormRef.setFieldsValue({ feeCde: res.body.code, feeTypeId: '1', status: '0' })
  }

  // 确认新增触发表单验证
  const handleAddOk = () => {
    // 表单验证
    addFormRef.validateFields().then(async () => {
      // 获取新增表单的值
      var response = addFormRef.getFieldsValue()
      console.log(response);
      if (!response.fee && !response.singleFee) {
        message.error('单笔交易收费占比, 单笔交易收费(HPC) 至少配置一项')
        return
      }
      if (response.singleFee > response.highestFee) {
        message.error('单笔交易收费(HPC) 应小于等于 单笔最高费率(HPC)')
        return
      }
      if (response.status === '1') {
        setIsModalValidation(true)
        setResponse(response)
        return
      }
      setAddLoading(true)
      await addWithdrawalRataInfo(response)
      setAddLoading(false)
      // 重置表单
      addFormRef.resetFields();
      // 关闭模态框
      setIsModalVisible(false)
      // 表格重新渲染
      actionRef.current?.reload()
    }).catch(() => { })
  }

  // 新增确认模态框确认按钮
  const handleOkValidation = async () => {
    console.log(response);

    // 调用新增接口
    setAddLoading(true)
    await addWithdrawalRataInfo(response)
    setAddLoading(false)
    // 重置表单
    addFormRef.resetFields();
    // 关闭模态框
    setIsModalValidation(false)
    setIsModalVisible(false)
    // 表格重新渲染
    actionRef.current?.reload()
  }

  // 点击生效、失效保存编号
  const handleActive = (record: object) => {
    // 获得要传递的参数feeCde 手续费编号
    const { feeCde } = record
    // 保存数据
    setFeeCde(feeCde)
  }

  // 确认生效
  const confirmActive = async () => {
    let data = {
      feeCde
    }
    // 生效
    let res = await activate(data)
    console.log(res);
    if (res) {
      // 表格重新渲染
      actionRef.current?.reload()
      // 成功
      message.success('生效成功');
    }
  }

  // 失效确认
  const confirmInvalidation = async () => {
    let res = await invalidation({ feeCde })
    if (res) {
      // 表格重新渲染
      actionRef.current?.reload()
      // 成功
      message.success('失效成功');
    }
  }


  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData
  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) =>
    record.status === '0' ?
      <Popconfirm
        title="是否生效该费率?"
        onConfirm={confirmActive}
        okText="是"
        cancelText="否"
      >
        <a key={record.status} onClick={() => handleActive(record)}>
          生效
        </a>
      </Popconfirm> :
      record.status === '1' ?
        <Popconfirm
          title="是否失效该费率?"
          onConfirm={confirmInvalidation}
          okText="是"
          cancelText="否"
        >
          <a key={record.status} onClick={() => handleActive(record)}>
            失效
          </a>
        </Popconfirm> : null

  // 定义金额单元格
  const amount: any = (text: number) => [
    <p
      key='amount'
      style={{ textAlign: 'right', margin: 0 }}
    >
      {typeof text === 'number' ? text.toFixed(5) : null}
    </p>
  ]
  // 费率单元格
  const fee: any = (text: number) => {
    return [<p
      key='fee'
      style={{ margin: 0 }}
    >
      {typeof text === 'number' ? `${(text * 100).toFixed(2)}%` : null}
    </p>]
  }
  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? item.render = actionRender : undefined
    item.dataIndex === 'fee' ? item.render = fee : undefined
    item.dataIndex === 'singleFee' ||
      item.dataIndex === 'highestFee' ?
      item.render = amount : undefined
  });

  // Table action 的引用，便于自定义触发，为了下面的reload
  const actionRef = React.useRef<ActionType>();

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle={<TableTitle title='费率管理' />}
        scroll={{ x: 900 }}
        actionRef={actionRef}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={
          async params => {
            console.log(params);

            let data = await getWithdrawalRataList({ ...params, pageNum: params.current })
            console.log(data);
            const result = {
              data: data.body.list,
              total: data.body.total,
            }
            return result;
          }
        }
        rowKey="feeCde"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        //设置工具栏按钮及事件
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary" onClick={addInfo}>
            新增
          </Button>
        ]}
      />
      {/* 新增模态框 */}
      <Modal
        title="费率配置"
        centered
        visible={isModalVisible}
        okButtonProps={{
          loading: addLoading
        }}
        onOk={handleAddOk}
        onCancel={() => { setIsModalVisible(false), addFormRef.resetFields(); }}
        width={700}>
        <Form
          form={addFormRef}
          name="basic"
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          initialValues={{ status: '1', feeTypeId: 1 }}
          autoComplete="off"
        >
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="手续费编号"
                name="feeCde"
              >
                <Input maxLength={20} disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="费率类型"
                name="feeTypeId"
              >

                <Select style={{ width: '100%' }} >
                  {
                    listFee.map((item) => {
                      return <Option value={item.feeTypeId} key={item.feeTypeId}>{item.feeType}</Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="状态"
                name="status"
              >
                <Select style={{ width: '100%' }} >
                  <Option value="0">未生效</Option>
                  <Option value="1">生效</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={8}>
              <Form.Item
                label="费率(%)"
                name="fee"
              >
                <InputNumber style={{ width: '100%' }} min={0} max={99} step={0.01} precision={2} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="单笔交易收费(HPC)"
                name="singleFee"
              >
                <InputNumber style={{ width: '100%' }} min={0} precision={5} maxLength={20} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="单笔最高费率(HPC)"
                name="highestFee"
                rules={[
                  {
                    required: true,
                    message: '不可为空'
                  }
                ]}
              >
                <InputNumber style={{ width: '100%' }} min={0} precision={5} maxLength={20} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={16}>
              <Form.Item
                label="备注"
                name="remark"
              >
                <TextArea
                  maxLength={50}
                  style={{ height: 60 }}
                  placeholder="请输入备注内容"
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 新增生效确认 */}
      <Modal
        visible={isModalValidation}
        onOk={handleOkValidation}
        okButtonProps={{
          loading: addLoading
        }}
        onCancel={() => {
          setIsModalValidation(false)
        }}
        centered
      >
        <div
          style={{
            height: 60,
            lineHeight: '60px',
            textAlign: 'center',
            fontSize: 30,
            fontWeight: 500
          }}>
          确认生效当前费率配置
        </div>
      </Modal>
    </div>
  );
};